package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.StrategyContent;
import cn.wolfcode.trip.base.domain.StrategyDetail;
import cn.wolfcode.trip.base.mapper.StrategyContentMapper;
import cn.wolfcode.trip.base.mapper.StrategyDetailMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IStrategyDetailService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class StrategyDetailServiceImpl implements IStrategyDetailService {

    @Autowired
    private StrategyDetailMapper strategyDetailMapper;
    @Autowired
    private StrategyContentMapper strategyContentMapper;

    @Override
    public void update(StrategyDetail strategyDetail) {
        //修改发布时间
        if(strategyDetail.getState()==StrategyDetail.STATE_RELEASE) {
            strategyDetail.setReleaseTime(new Date());
        }
        strategyDetailMapper.updateByPrimaryKey(strategyDetail);
        //更新文本内容
        StrategyContent strategyContent=new StrategyContent();
        strategyContent.setId(strategyDetail.getId());
        strategyContent.setContent(strategyDetail.getStrategyContent().getContent());
        strategyContentMapper.updateByPrimaryKey(strategyContent);

    }

    @Override
    public void save(StrategyDetail strategyDetail) {
        //排序
        if(strategyDetail.getSequence()==null){
            int s=strategyDetailMapper.selectMaxSequence();
            strategyDetail.setSequence(s+1);
        }
        Date date=new Date();
        //创建时间
        strategyDetail.setCreateTime(date);
        //发布时间,先判断
        if(strategyDetail.getState()==StrategyDetail.STATE_RELEASE) {
            strategyDetail.setReleaseTime(date);
        }
        strategyDetailMapper.insert(strategyDetail);
        //保存文本内容
        StrategyContent strategyContent=new StrategyContent();
        strategyContent.setId(strategyDetail.getId());
        strategyContent.setContent(strategyDetail.getStrategyContent().getContent());
        strategyContentMapper.insert(strategyContent);
    }


    @Override
    public List<StrategyDetail> listAll() {
        return  strategyDetailMapper.selectAll();
    }

    @Override
    public PageInfo<StrategyDetail> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<StrategyDetail> list=strategyDetailMapper.selectForList(qo);
        return new PageInfo<>(list);
    }

    @Override
    public StrategyContent getContentById(Long id) {
        return strategyContentMapper.selectContentById(id);
    }

    @Override
    public StrategyDetail get(Long id) {
        return strategyDetailMapper.selectByPrimaryKey(id);
    }
}
